<template>
  <div class="fly-line-item">
    <div class="image-wrapper" @click="onClick">
      <el-image :src="img" fit="cover" lazy>
        <div slot="placeholder" class="image-slot">
          <div class="placeholder"></div>
        </div>
        <div slot="error" class="image-slot">
          <div class="placeholder"></div>
        </div>
      </el-image>
    </div>
    <span
      ref="titleRef"
      :contenteditable="editable"
      @dblclick="onDoubleClick"
      @blur="onBlur"
      >{{ title }}</span
    >
    <i
      v-if="category === 'custom'"
      class="el-icon-delete delete"
      @click="onDelete"
    ></i>
  </div>
</template>

<script>
export default {
  name: 'fly-line-item',
  props: [
    'title',
    'img',
    'id',
    'index',
    'category',
    'type'
  ],
  data() {
    return {
      editable: false
    }
  },
  methods: {
    onClick() {
      this.$emit('onItemClick', this.category, this.index)
    },
    onDoubleClick() {
      if (!this.editable) {
        this.editable = true
        console.log(this.$refs.titleRef)
        this.$refs.titleRef.focus()
        // this.$emit('onItemDoubleClick', this.category, this.index)
      }
    },
    onBlur(value) {
      this.editable = false
      console.log('blur', value)
    },
    onDelete() {
      this.$emit('onItemDelete', this.category, this.index)
    },
    onKeyDown(event) {
      console.log('onKeyDown', event)
      if (event.key === 'Enter') {
        event.preventDefault()
        this.$emit(
          'onEnterDown',
          this.category,
          this.index,
          this.$refs.titleRef.innerText
        )
        this.editable = false
      }
    }
  },
  watch: {
    editable(value) {
      if (value) {
        document.addEventListener('keydown', this.onKeyDown)
      } else {
        document.removeEventListener(
          'keydown',
          this.onKeyDown
        )
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.fly-line-item {
  position: relative;
  display: flex;
  flex-direction: column;
  cursor: pointer;

  .image-wrapper {
    height: 58px;

    .el-image {
      width: 100%;
      height: 100%;

      .image-slot {
        height: 100%;

        .placeholder {
          height: 100%;
          background-color: #a9a9a9;
        }
      }
    }
  }

  span {
    font-size: 14px;
    color: white;
    text-align: center;
    background-color: #0c87a8;
    padding: 4px 0;
  }

  .delete {
    display: none;
    position: absolute;
    top: 10px;
    right: 10px;
    padding: 3px;
    color: red;
  }

  &:hover {
    .delete {
      display: inline;
    }
  }
}
</style>
